using Sustainalytics.Universes.BusinessLogic;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Sustainalytics.Utils;
using System.Web.Http.Cors;

namespace Sustainalytics.Universes.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/files")]
    public class FilesController: ApiController, IFilesController
    {
        private readonly IUniversesManagement _universesManagement;

        public FilesController(IUniversesManagement universeManagement)
        {
            _universesManagement = universeManagement;
        }

        [HttpPost]
        [Route("")]
        public Task<HttpResponseMessage> Post()
        {
            try
            {
                var id = Guid.NewGuid();
                var filename = RemoveIllegalCharacters.Remove(Request.Content.Headers.ContentDisposition.FileName);
                var contentType = Request.Content.Headers.ContentType.ToString();
                var mongoData = _universesManagement.UploadFile(id, filename, contentType);

                var result = Request.Content.ReadAsStreamAsync().ContinueWith(task =>
                {
                    if (task.IsCanceled || task.IsFaulted)
                        throw new HttpRequestException();

                    using (mongoData.Item1)
                    {
                        task.Result.CopyTo(mongoData.Item1);
                         
                        var uploadLog = new ClientDW.Entities.Universes.UploadLog()
                        {
                            Created = DateTime.UtcNow,
                            UploadType = ClientDW.Entities.Universes.UploadType.UniversesUpload,
                            UserId = Guid.Empty,
                            FileId = id,
                            Id = Guid.NewGuid()
                        };

                        _universesManagement.AddUploadLogs(uploadLog);

                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                });
                return result;
            }
            catch (Exception ex)
            {
                return (new Task<HttpResponseMessage>(() => Request.CreateResponse(HttpStatusCode.InternalServerError,ex.Message)));
            }
        }

        [Route("")]
        public HttpResponseMessage Get(bool isProcessing = false)
        {
            try
            {
                if (isProcessing)
                    return Request.CreateResponse(HttpStatusCode.OK, _universesManagement.IsProcessingScheduled());

                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
    }
}
